import axios from 'axios'  
import router from "@/router"
import { Notice } from 'view-design';
// import qs from "qs"
axios.defaults.baseURL = process.env.VUE_APP_HOST
axios.interceptors.request.use(config => {
        if(!config.data) config.data={}
        config.headers['X-Requested-With']='XMLHttpRequest'
        const type=localStorage.getItem('currentIdentity')
        if(type){
            config.data[type+'id']=localStorage.getItem(type+'id')
            config.headers['http-x-token'] = localStorage.getItem('token')
        }
        return config;
    },err => {
        Notice.error({
            title:'网络连接失败',
            desc: '客户端通讯出错'
        })
        return Promise.resolve(err);
    }
)

axios.interceptors.response.use(res => {
    if(!res.data){  //没有任何数据
        Notice.error({
            title:'通信失败',
            desc: '服务器没有响应'
        })
        return  
    }
    switch(res.data.code){
        case 0:
            return res.data
        case 401:
        case 402:
            localStorage.clear()
            Notice.error({
                title:'账户过期',
                desc: '你的账号已过期，请重新登录'
            })
            router.push({path:'/'})
        break
        default:
            Notice.error({
                title:'通信失败',
                desc: res.data.msg ||'数据异常' 
            })
        break 
    }
    

    },err => {
        Notice.error({
            title:'通信失败',
            desc: '无法连接服务器',
        })
        throw new Error(err);  
    }
    
)
export default axios